package datasource

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"superstar/conf"
	"sync"
	"xorm.io/xorm"
)

// 数据库单例 dbhelper.go
var (
	masterEngine *xorm.Engine
	slaveEngine  *xorm.Engine
	lock         sync.Mutex
)

func InstanceMaster() *xorm.Engine {
	if masterEngine != nil {
		return masterEngine
	}

	lock.Lock()
	defer lock.Unlock()

	// 协程时，上面十个一起进来，每个都到 lock.Lock() 加锁挂起。这里避免 第一个加锁然后创建实例后，每个都创建实例
	if masterEngine != nil {
		return masterEngine
	}

	c := conf.MasterDbConf
	driverSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		c.User, c.Pwd, c.Host, c.Port, c.DbName)
	fmt.Println(driverSource)

	masterEngine, err := xorm.NewEngine(conf.DriverName, driverSource)
	if err != nil {
		log.Fatal("dbhelper.DbInstanceMaster err:", err)
		return nil
	}

	// DEBUG 模式，打印全部sql, 帮助对比 orm 与 sql 执行对照关系
	masterEngine.ShowSQL(false)
	masterEngine.SetTZLocation(conf.SysTimeLocation)

	return masterEngine
}

func InstanceSlave() *xorm.Engine {
	if slaveEngine != nil {
		return slaveEngine
	}

	lock.Lock()
	defer lock.Unlock()

	// 协程时，上面十个一起进来，每个都到 lock.Lock() 加锁挂起。这里避免 第一个加锁然后创建实例后，每个都创建实例
	if slaveEngine != nil {
		return slaveEngine
	}

	c := conf.MasterDbConf
	driverSource := fmt.Sprint("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		c.User, c.Pwd, c.Host, c.Port, c.DbName)

	slaveEngine, err := xorm.NewEngine(conf.DriverName, driverSource)
	if err != nil {
		log.Fatal("dbhelper.DbInstanceMaster err:", err)
		return nil
	}

	return slaveEngine
}
